<?php require_once Q::ini ( 'app_config/ROOT_DIR' ) . '/app/helper/wxpayapi.php'; ?>
<?php class Controller_Wechatpay extends Controller_Abstract
{
    // function _before_execute(){
    //     if(defined("NTS_USERS_WECHAT") && NTS_USERS_WECHAT == TRUE){
            
    //     }else{
    //         exit("此功能尚未授权");
    //     }
    // }
    /*
     * 充多少到多少展示页面
     */
    function actionPayChoose(){
        $aid=intval($this->_context->aid);
        $acctname = trim($this->_context->acctname);
        $userobj=Acctuser::find('acctname=? and agent_id=?',$acctname,$aid)->getOne();
        if(!$userobj->id()){
            exit('该用户不存在');
        }
//         $acct = Acct::find('id = ?',$aid)->getOne();
//         if($userobj->mz_agentid != $acct->bind_mzid){
            $sql = "select distinct(balance) from app_mz.mz_card_".$userobj->agent_id.' where agent_id = '.$userobj->mz_agentid .' and used = 0';
            $balance = QDB::getConn()->execute($sql)->fetchAll();
            if(count($balance) ==0) {
                $msg = '充值卡已售空';
                header('location: /wechatpay/payerror/msg/'.urlencode($msg));
                exit();
            }
            //echo $sql;die;
          // dump($balance);die;
            $need = Helper_Array::toHashmap($balance, 'balance','balance');
            $needarray = $need;
        //   dump($needarray);die;
          $paysetobj=userpayset::find(array('agent_id'=>$userobj->agent_id,'balanceto'=>$needarray,'mz_acctid'=>$userobj->mz_agentid))->getAll();
        
//         }else{
//           $paysetobj=userpayset::find('agent_id=? ',$userobj->agent_id)->getAll();
//         }
      
        if(count($paysetobj)==0){
            $msg = '代理尚未设置充值金额和到账额度比例';
            header('location: /wechatpay/payerror/msg/'.urlencode($msg));
            exit();
        }
        $this->_view['acctname'] = $acctname;
        $this->_view['paysetobj'] = $paysetobj;
        $this->_view['aid'] = $aid;
    }
    /*
	 * 手机用户支付宝充值确认界面
	*/
	function actionwechatpay()
	{   

	    if($this->_context->isPOST())
	    {
	        $acctname = trim($this->_context->acctname);
	        $result =array('code'=>'','msg'=>'');
	        $payfees=($this->_context->payfee);
	        $balanceto=intval($this->_context->balanceto);
	        $aid=intval($this->_context->aid);
	        $userobj=Acctuser::find('acctname=? and agent_id=?',$acctname,$aid)->getOne();
	        if(!$userobj->id()){
	            $result = array('code'=>1,urlencode('用户不存在'));
	            exit(json_encode($result));
	        }
	        $mzacctobj=mzacct::find('id=?',$userobj->mz_agentid)->setColumns('id,wxmchid,wxkey,wxappid,wxappsecret')->getOne();
	        if(!$mzacctobj->id()){
	            $result = array('code'=>2,'msg'=>urlencode('用户所属商家不存在'));
	            exit(json_encode($result));
	        }
	        //dump($acctobj);die;
	        $wxmchid=trim($mzacctobj->wxmchid);
	        $wxkey=trim($mzacctobj->wxkey);
	        $wxappid=trim($mzacctobj->wxappid);
	        $wxappsecret = trim($mzacctobj->wxappsecret);
	        if(!$wxmchid || !$wxkey ||!$wxappid || !$wxappsecret){
	            $result = array('code'=>3,'msg'=>urlencode('微信配置不完整'));
	            exit(json_encode($result));

	        }
	        $pay_total = sprintf('%.2f', $payfees)*100;
	        $order_id = ordervoucher::get_order_id($userobj->id);
	        // 调用支付宝进行支付
	        $config = array(
	                'APPID'=>$wxappid,
	                'MCHID'=>$wxmchid,
	                'WXKEY'=> $wxkey,
	                'APPSECRET'=>$wxappsecret,
	                'ip'=>Helper_Common::get_ip(),
	        );
	        $data = array(
	                'user_id'=>$userobj->id,
	                'payfee'=>$payfees,
	                'balanceto'=>$balanceto
	                );
	       
	        WxPayConfig::setconfig($mzacctobj);
	        $body = '微信在线支付';
	        $url = Helper_Common::getRequestHost();
	        $notityUrl = $url . "wxnotify/callback";
	        $trade_type = 'APP';
	        $Device_info='WEB';
	        
	        
	        
	        //给需要提交的必须参数赋值
	        $wxpay = new WxPayUnifiedOrder();
	        $wxpay->SetDevice_info($Device_info);
	        $wxpay->SetBody($body);
	        $wxpay->SetOut_trade_no($order_id);
	        $wxpay->SetTotal_fee($pay_total);
	        $wxpay->SetNotify_url($notityUrl);
	        $wxpay->SetTrade_type($trade_type);
	        $wxpay->SetAttach(json_encode($data));
	         
	        $result =  Helper_WxPayApi::unifiedOrder($wxpay, $config);
	        if(is_array($result) && $result['result_code'] == 'SUCCESS' && $result['appid'] == $wxappid ){
	            $sql =  'select id,cardpass,rategroupid,rategroupid_acall from app_mz.mz_card_'.$aid.' where agent_id = '.$userobj->mz_agentid.' and  balance = '.$balanceto.' and used = 0  order by id desc limit 1';
	            $id  = QDB::getConn()->execute($sql)->fetchRow();	            
	            if( $id['id'] && ($userobj->rategroupid != $id['rategroupid'] || $userobj->rategroupid_acall != $id['rategroupid_acall'])){	                
	               $result = array('code'=>99,'msg'=>$result['prepay_id']);
	            }else{
	                $result = array('code'=>0,'msg'=>$result['prepay_id']);
	            }	            	           
	            exit(json_encode($result));
	        }else{
	            $result = array('code'=>4,'msg'=>$result['return_msg']);
	            Helper_Common::log(print_r($result,true),'applyback');
	            exit(json_encode($result));	          
	         
	        }	       
	    }else{
	        $prepayid=trim($this->_context->prepayid);
	        $acctname = trim($this->_context->acctname);
	        $payfees=sprintf('%.2f',$this->_context->payfee);
	        $balanceto=intval($this->_context->balanceto);
	        $this->_view['payfees'] = $payfees;
	        $this->_view['balanceto'] = $balanceto;
	        $this->_view['acctname'] = $acctname;
	        $this->_view['prepayid'] = $prepayid;
	    }

	}
	/*
	 * 参数请求错误提示
	*/
	function actionRequestError() {
	    
	}
	function actionPayError() {
	    $msg = trim($this->_context->msg);
	    $msg = urldecode($msg);
	    $msg = empty($msg)?'':$msg;
	    $this->_view['msg'] = $msg;
	}
	function actionimportwechatpay()
	{
	
	    if($this->_context->isPOST())
	    {
	        $acctname = trim($this->_context->acctname);
	        $result =array('code'=>'','msg'=>'');
	        $aid=intval($this->_context->aid);
	        $userobj=Acctuser::find('acctname=? and agent_id=?',$acctname,$aid)->getOne();
	        if(!$userobj->id()){
	            $result = array('code'=>1,urlencode('用户不存在'));
	            exit(json_encode($result));
	        }
	         $o = mzcardimport::find('agent_id = ? and used = 0',$aid)->getOne();
	       	 $mzacctobj = mzacct::find('voip_agentid = ?',$aid)->order('id asc')->getOne();
	        if(!$mzacctobj->id()){
	            $result = array('code'=>2,'msg'=>urlencode('用户所属商家不存在'));
	            exit(json_encode($result));
	        }
	        if($mzacctobj->cardin_name && $mzacctobj->cardin_price && $o->id()){
	             
	        }else{
	            $msg ='尚未设置外部导入卡名称价格或尚无外部导入卡';
	            header('location: /taobao/payerror/msg/'.urlencode($msg));
	            exit();
	        }
	        //dump($acctobj);die;
	        $wxmchid=trim($mzacctobj->wxmchid);
	        $wxkey=trim($mzacctobj->wxkey);
	        $wxappid=trim($mzacctobj->wxappid);
	        $wxappsecret = trim($mzacctobj->wxappsecret);
	        if(!$wxmchid || !$wxkey ||!$wxappid || !$wxappsecret){
	            $result = array('code'=>3,'msg'=>urlencode('微信配置不完整'));
	            exit(json_encode($result));
	
	        }
	        $pay_total = sprintf('%.2f', $mzacctobj->cardin_price)*100;
	        $order_id = ordervoucher::get_order_id($userobj->id);
	        // 调用支付宝进行支付
	        $config = array(
	                'APPID'=>$wxappid,
	                'MCHID'=>$wxmchid,
	                'WXKEY'=> $wxkey,
	                'APPSECRET'=>$wxappsecret,
	                'ip'=>Helper_Common::get_ip(),
	        );
	        $data = array(
	                'user_id'=>$userobj->id,
	                'payfee'=>$mzacctobj->cardin_price,
	        );
	
	        WxPayConfig::setconfig($mzacctobj);
	        $body = '微信在线支付';
	        $url = Helper_Common::getRequestHost();
	        $notityUrl = $url . "wxnotify/importcallback";
	        $trade_type = 'APP';
	        $Device_info='WEB';
	         
	         
	         
	        //给需要提交的必须参数赋值
	        $wxpay = new WxPayUnifiedOrder();
	        $wxpay->SetDevice_info($Device_info);
	        $wxpay->SetBody($body);
	        $wxpay->SetOut_trade_no($order_id);
	        $wxpay->SetTotal_fee($pay_total);
	        $wxpay->SetNotify_url($notityUrl);
	        $wxpay->SetTrade_type($trade_type);
	        $wxpay->SetAttach(json_encode($data));
	
	        $result =  Helper_WxPayApi::unifiedOrder($wxpay, $config);
	        if(is_array($result) && $result['result_code'] == 'SUCCESS' && $result['appid'] == $wxappid ){
	            $result = array('code'=>0,'msg'=>$result['prepay_id']);        
	            exit(json_encode($result));
	        }else{
	            $result = array('code'=>4,'msg'=>$result['return_msg']);
	            Helper_Common::log(print_r($result,true),'applyback');
	            exit(json_encode($result));
	
	        }
	    }else{
	        $prepayid=trim($this->_context->prepayid);
	        $acctname = trim($this->_context->acctname);
	        $aid = trim($this->_context->aid);
	        $payfees=sprintf('%.2f',$this->_context->payfee);
	        $this->_view['payfees'] = $payfees;
	        $this->_view['acctname'] = $acctname;
	        $this->_view['prepayid'] = $prepayid;
	        $this->_view['aid'] = $aid;
	    }
	
	}
}
	